package misc

import (
	"math"
	"strings"
)

// Hex2Int 十六进制字符串转换为整数。
// hexadecimal string to integer.
func Hex2Int(s string) (n int, ok bool) {
	s = strings.TrimLeft(strings.TrimLeft(s, "0x"), "0X")

	n = 0
	for i := 0; i < len(s); i++ {
		if '0' <= s[i] && s[i] <= '9' {
			n *= 16
			n += int(s[i] - '0')
		} else if 'a' <= s[i] && s[i] <= 'f' {
			n *= 16
			n += int(s[i]-'a') + 10
		} else if 'A' <= s[i] && s[i] <= 'F' {
			n *= 16
			n += int(s[i]-'A') + 10
		} else {
			return 0, false
		}

		// not too big to worry about overflow
		if n >= math.MaxInt32 {
			return 0, false
		}
	}

	return n, true
}
